-- 感谢@狸猫
-- 建议使用LuaDB
-- SimpleDataStore (cjson版)
if not table.clone then

    function table.clone(orig)
        if type(orig) ~= "table" then
            return orig
        end

        local copy = {}
        for orig_key, orig_value in pairs(orig) do
            copy[table.clone(orig_key)] = table.clone(orig_value)
        end

        setmetatable(copy, table.clone(getmetatable(orig)))
        return copy
    end

end

local SimpleDataStore = setmetatable({}, {
    __call = function(self, ...)
        return self:new(...)
    end,
    __index = self
})

SimpleDataStore.json = require "cjson"
local cjson = SimpleDataStore.json
local io = io
local string = string

-- 获取应用对应Android/data目录
SimpleDataStore.ExternalFilesDir = tostring(activity.getExternalFilesDir(nil))

function SimpleDataStore:new(BaseName)
    local o = table.clone(self)
    BaseName = type(BaseName) == "string" and BaseName or "default"
    o._FilePath = SimpleDataStore.ExternalFilesDir .. "/" .. BaseName .. ".conf"
    o._fileW = io.open(o._FilePath, "wb")
    o._fileR = io.open(o._FilePath, "rb")
    return o
end

-- 数据过长时可能需要增加数据长度
---@param update boolean 是否移动指针至文件头
function SimpleDataStore:set(key, value, update)
    if update then
        self._fileW:seek("set", 0)
    end
    local str = cjson.encode({
        [key] = value
    })
    local len = string.len(str)

    -- 写入数据长度，使用 ">I6" 格式化字符串，确保长度为6字节
    self._fileW:write(string.pack(">I6", len))
    self._fileW:write(str) -- 写入序列化后的数据
    self._fileW:flush()

    return self
end

function SimpleDataStore:get(key)
    local lenStr = self._fileR:read(6) -- 读取数据长度
    if not lenStr then
        return nil
    end

    local len = string.unpack(">I6", lenStr)
    local dataStr = self._fileR:read(len) -- 根据长度读取序列化后的数据
    if not dataStr or string.len(dataStr) ~= len then
        return nil
    end

    local data = cjson.decode(dataStr)
    return data and data[key] or nil
end

function SimpleDataStore:removeFile()
    -- 原生Lua使用io.lnfo 返回nil即不存在，存在则返回table
    if io.isdir(self._FilePath) then
        os.remove(self._FilePath)
    end
end

function SimpleDataStore:close()
    if self._fileW then
        self._fileW:close()
    end
    if self._fileR then
        self._fileR:close()
    end
end

return SimpleDataStore

--[[ 
-- 创建 Data 对象
local Data = SimpleDataStore("sample")

-- 写入键值对
Data:set("key", "value")

-- 读取
print(Data:get("key"))

-- 删除键值对
Data:set("key", nil, true)

-- 销毁对象
Data:close()
Data = nil

 ]]
